# coding=utf-8
# author=haishan09@gmail.com
from django import forms
from django.contrib.auth import get_user_model
from treemenu.models import Menu, MenuItem

UserModel = get_user_model()

class MenuItemForm(forms.ModelForm):

    class Meta:
        model = MenuItem
        exclude = ('level', 'rank')


class MenuForm(forms.ModelForm):

    class Meta:
        model = Menu
        fields  = ['label', ]

    def save(self, commit=False):
        menu = super(MenuForm, self).save(commit=commit)
        if not menu.root_id:
            root_menuitem = MenuItem(label='root', level=0, rank=0) 
            root_menuitem.save()
            setattr(menu, 'root_id', root_menuitem.pk)
        return menu


class MenuUserPermsAdminForm(forms.ModelForm):

    class Meta:
        model = Menu
        fields  = ['label', ]

    def __init__(self, *args, **kwargs):
        super(MenuUserPermsAdminForm, self).__init__(*args, **kwargs)
        self.fields['user'] = forms.ChoiceField(
            label=u'用户', 
            choices=[(u.pk, u) for u in UserModel.objects.exclude(pk=1)],
            widget=forms.Select(attrs={'onchange': 'user_change(this)'})
        )
        self.fields['checked_menuitems'] = forms.CharField(
            label=u'权限列表', 
            widget=forms.HiddenInput
        )
        self.fields['unchecked_menuitems'] = forms.CharField(
            label=u'权限列表', 
            widget=forms.HiddenInput
        )

class MenuGroupPermsAdminForm(forms.ModelForm):

    class Meta:
        model = Menu
        fields  = ['label', ]

    def __init__(self, *args, **kwargs):
        super(MenuGroupPermsAdminForm, self).__init__(*args, **kwargs)
        self.fields['group'] = forms.ChoiceField(
            label=u'用户', 
            choices=[(u.pk, u) for u in UserModel.objects.exclude(pk=1)],
            widget=forms.Select(attrs={'onchange': 'user_change(this)'})
        )
